import java.util.PriorityQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

class MyThreadPool {
    private Thread[] arrThread;
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>(100);
    private Object locker = new Object();

    public MyThreadPool(int poolSize) {
        arrThread = new Thread[poolSize];
        for (int i = 0; i < poolSize; i++) {
            int id = i;
            Thread t = new Thread(() -> {
               while(true) {
                   try {
                       synchronized (locker) {
                           while(queue.isEmpty()) {
                               locker.wait();
                           }
                           MyTimerTask task = queue.peek();
                           if (task.getTime() >= System.currentTimeMillis()) {
                               task.getTask().run();
                               queue.poll();
                           } else {
                               locker.wait(task.getTime() - System.currentTimeMillis());
                           }
                       }
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
               }
            },"" + id);
            t.start();
            arrThread[i] = t;
        }
    }

    public void schedule(Runnable task, long delay) throws InterruptedException {
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(task, System.currentTimeMillis() + delay);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }
}

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long time;

    public MyTimerTask(Runnable task, long time) {
        this.task = task;
        this.time = time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    public Runnable getTask() {
        return task;
    }

    public long getTime() {
        return time;
    }
}

public class Demo6 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0; i < 100000; i++) {
            int id = i;
            pool.schedule(()->{
                System.out.println(id);
            }, 1000);
        }
    }
}
